package com.qsl.ssyx.home.service.impl;

import com.qsl.ssyx.client.activity.ActivityFeignClient;
import com.qsl.ssyx.client.product.ProductFeignClient;
import com.qsl.ssyx.client.search.SkuFeignClient;
import com.qsl.ssyx.home.service.ItemService;
import com.qsl.ssyx.vo.product.SkuInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@Service
public class ItemServiceImpl implements ItemService {

    //  线程池
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired
    private ActivityFeignClient activityFeignClient;
    @Autowired
    private SkuFeignClient skuFeignClient;

    //    根据商品Id及用户id获取商品详情
    @Override
    public Map<String, Object> SkuInfoBySkuIdAndUserId(Long skuId, Long userId) {
        //   使用线程池来提升以下三部访问速度

        // 封装最终返回数据
        Map<String, Object> result = new HashMap<>();

        // 1.根据商品id获取商品信息
        CompletableFuture<SkuInfoVo> futureSkuInfoVo = CompletableFuture.supplyAsync(() -> {
            SkuInfoVo skuInfoVo = productFeignClient.getSKuInfoVoBySkuId(skuId);
            result.put("skuInfoVo", skuInfoVo);
            return skuInfoVo;
        }, threadPoolExecutor);

        // TODO 判断是否为秒杀商品


        // 2. 根据商品id和用户id获取优惠卷信息-普通商品
        CompletableFuture<Void> futureCouponInfo = CompletableFuture.runAsync(() -> {
            Map<String, Object> activityMap = activityFeignClient.getActivityInfoBySkuIdAndUserId(skuId, userId);
            result.putAll(activityMap);
        }, threadPoolExecutor);


        // 3. 根据skuId更新ES索引库的商品热度信息，+1
        CompletableFuture<Void> futureSKuHotScore = CompletableFuture.runAsync(() -> {
            skuFeignClient.inerSkuHotScore(skuId);
        }, threadPoolExecutor);

        //任务组合
        CompletableFuture.allOf(futureSkuInfoVo, futureCouponInfo, futureSKuHotScore).join();

        return result;
    }
}
